package controller

import (
	"encoding/json"
	"fmt"
	"gin/common"
	"gin/model"
	"gin/response"
	"github.com/gin-gonic/gin"
	"strconv"
	"strings"
)

func AddCard(ctx *gin.Context) {
	goodsId := ctx.PostForm("goodsId")
	sku := ctx.PostForm("sku")       //规格
	number := ctx.PostForm("number") //数量
	num, _ := strconv.Atoi(number)
	if num < 1 {
		num = 1
	}
	if len(goodsId) == 0 {
		response.Fail(ctx, gin.H{}, "缺少商品")
	}
	var goodsInfo model.Goods
	Db := common.GetDB()
	Db.Debug().Table("cat_meal_goods").Where("id = ? AND status = 1", goodsId).First(&goodsInfo)
	var priceStr float64
	if len(sku) == 0 {
		priceStr = goodsInfo.MinPrice
	} else {
		//[{"optionId":41223,"optionValueId":430950}]
		var result []model.CartOption //json转数组
		err := json.Unmarshal([]byte(sku), &result)
		if err != nil {
			response.Error(ctx, 500, gin.H{}, "传入格式有误")
			return
		}
		var s string
		for _, item := range result {
			s += strconv.Itoa(item.OptionId) + ":" + strconv.Itoa(item.OptionValueId) + ","
		}
		var price model.SkuPrice
		Db.Debug().Table("cat_meal_goods_sku").Where("propertyChildIds = ?", s).Select("price").First(&price)
		priceStr = price.Price
	}
	user, _ := ctx.Get("user")
	var cart model.CartStruct
	Db.Debug().Table("cat_meal_cart").Where("uid = ? and goodsId=? and sku=?", user.(model.UserInfo).Uid, goodsId, sku).First(&cart)
	if cart.Id > 0 {
		Db.Debug().Table("cat_meal_cart").Where("id =?", cart.Id).Update("number", cart.Number+1)
	} else {
		newGoodsId, _ := strconv.Atoi(goodsId)
		insert := model.CartStruct{
			Uid:     user.(model.UserInfo).Uid,
			Number:  num,
			Price:   priceStr,
			Name:    goodsInfo.Name,
			GoodsId: newGoodsId,
			Sku:     sku,
			Pic:     goodsInfo.Pic,
			ShopId:  goodsInfo.ShopId,
		}
		Db.Debug().Table("cat_meal_cart").Create(&insert)
	}
	response.Success(ctx, gin.H{}, "添加成功")
}

// CardList 购物车列表
func CardList(ctx *gin.Context) {
	user, _ := ctx.Get("user")
	shopId := ctx.PostForm("shopId")
	if len(shopId) == 0 {
		response.Fail(ctx, gin.H{}, "缺少店铺标识")
		return
	}
	var cart, showCart []model.CartStruct
	m := map[int]*model.CartStruct{}
	Db := common.GetDB()
	Db.Debug().Table("cat_meal_cart").Where("uid = ? and shop_id =?", user.(model.UserInfo).Uid, shopId).Find(&cart)
	var price float64
	var num int

	for _, value := range cart {
		num += value.Number
		price += value.Price
		if len(value.Sku) > 3 {
			var opPro []model.CartOption
			fmt.Println("value.Sku:", value.Sku)
			err := json.Unmarshal([]byte(value.Sku), &opPro)
			if err != nil {
				fmt.Println("err:", err)
				response.Error(ctx, 500, gin.H{}, "系统错误")
				return
			}
			for key, v := range opPro {
				var propertiesName, optionName NameStruct
				Db.Debug().Table("cat_meal_goods_properties").Where("id = ?", v.OptionId).First(&propertiesName)
				Db.Debug().Table("cat_meal_goods_option").Where("id = ?", v.OptionValueId).First(&optionName)
				OptionList := model.OptionStruct{
					OptionId:        v.OptionId,
					OptionName:      propertiesName.Name,
					OptionValueId:   v.OptionValueId,
					OptionValueName: optionName.Name,
				}
				value.SkuList = append(value.SkuList, OptionList)
				m[key] = &value
			}
		}

	}
	for _, v := range m {
		if len(v.SkuList) > 0 {
			showCart = append(showCart, *v)
		}
	}
	response.Success(ctx, gin.H{"list": showCart}, "success")
}

// ModifyNumber 数量
func ModifyNumber(ctx *gin.Context) {
	id := ctx.PostForm("id")
	if len(id) == 0 {
		response.Fail(ctx, gin.H{}, "缺少购物车标识")
		return
	}
	num := ctx.PostForm("number")
	if num2, _ := strconv.Atoi(num); num2 <= 0 {
		response.Fail(ctx, gin.H{}, "缺少数量")
		return
	}
	user, _ := ctx.Get("user")
	var cart model.CartStruct
	Db := common.GetDB()
	Db.Debug().Table("cat_meal_cart").Where("uid = ? and id =?", user.(model.UserInfo).Uid, id).First(&cart)
	fmt.Println(cart)
	if cart.Id == 0 {
		response.Fail(ctx, gin.H{}, "购物车记录不存在")
		return
	}
	Db.Debug().Table("cat_meal_cart").Where("uid = ? and id =?", user.(model.UserInfo).Uid, id).Update("number", num)
	response.Success(ctx, gin.H{}, "success")
}

type NameStruct struct {
	Name string `gorm:"column:name"`
}

// EmptyCart 清空购物车
func EmptyCart(ctx *gin.Context) {
	user, _ := ctx.Get("user")
	shopId := ctx.PostForm("shopId")
	if len(shopId) == 0 {
		response.Fail(ctx, gin.H{}, "缺少店铺标识")
		return
	}
	var cart model.CartStruct
	Db := common.GetDB()
	Db.Debug().Table("cat_meal_cart").Where("uid = ? and shop_id =?", user.(model.UserInfo).Uid, shopId).Delete(&cart)
	response.Success(ctx, gin.H{}, "success")
}

// Remove 删除购物车
func Remove(ctx *gin.Context) {
	user, _ := ctx.Get("user")
	idStr := ctx.PostForm("id")
	if len(idStr) == 0 {
		response.Fail(ctx, gin.H{}, "缺少购物车标识")
		return
	}
	sli := strings.Split(idStr, ",")
	var cart model.CartStruct
	Db := common.GetDB()
	Db.Debug().Table("cat_meal_cart").Where("uid = ? and id in (?)", user.(model.UserInfo).Uid, sli).Delete(&cart)
	response.Success(ctx, gin.H{}, "success")
}
